<template>
  <view v-if="update" class="bgColor" style="padding-bottom: calc(var(--window-bottom) + 50px);">

    <view>
      <!--      <imgsBanner-tag :imgList='imgList' autoplay duration='500' interval="5000" :currentImg='currentImg'
                            :isShowSmallImgs='true' customizeDisplayField='url' @change='onChange'></imgsBanner-tag> -->
      <u-swiper
          :list="imgList"
          height="600"
      ></u-swiper>
    </view>

    <view
        style="width: 95%;margin: auto;padding: 30rpx;background-color:white;border-radius: 20rpx;margin-top: 30rpx">
      <view style="width: 100%;">
        <text style="color: red;font-size: 30rpx;font-weight: 600">￥</text>
        <text style="color: red;font-size: 36rpx;font-weight: 600" v-if="good.minPrice!=good.maxPrice">{{ good.minPrice }}-{{ good.maxPrice }}</text>
        <text style="color: red;font-size: 36rpx;font-weight: 600" v-else>{{ good.minPrice }}</text>
      </view>

      <view style="width: 100%;">
        <text text style="font-size: 32rpx;font-weight: 600">{{ good.description }}</text>
      </view>
    </view>

    <view style="width: 95%;margin: auto;padding: 30rpx;border-radius: 20rpx;margin-top: 30rpx;background-color:white;">
      <u-form
          labelPosition="left"
          :model="good"
          ref="form1"
      >
        <u-form-item
            label="规格"
            prop="specification"
            ref="item1"
            borderBottom
        >
          <u-input
              v-model="good.specification"
              disabled
              :border=false
              @click="openSelect"
              disabledColor="#ffffff"
              placeholder="请选择"

          ></u-input>
          <u-icon
              slot="right"
              name="arrow-right"
          ></u-icon>
        </u-form-item>

        <u-form-item
            label="数量"
            prop="count"
            ref="item2"
            borderBottom
        >
          <u-input
              v-model="good.count"
              disabled
              :border=false
              @click="openSelect"
              disabledColor="#ffffff"
              placeholder="请选择"
          ></u-input>
          <u-icon
              slot="right"
              name="arrow-right"
          ></u-icon>
        </u-form-item>
      </u-form>
    </view>
    <view style="width: 95%;margin: auto;padding: 30rpx;border-radius: 20rpx;margin-top: 30rpx;background-color:white;">
      <view>
        <text style="font-weight: 600">宝贝评价({{evaluateCount}})</text>
        <view style="color: rgba(255,136,0,0.88);float: right" @click="moreEvaluate"><text>查看全部</text><uni-icons color="rgba(255,136,0,0.88)" type="right" size="16"></uni-icons></view>
      </view>
      <uni-evaluate :list-data="evaluate" :show-head="false"></uni-evaluate>
    </view>


    <view style="width: 95%;margin: auto;padding: 30rpx;border-radius: 20rpx;margin-top: 30rpx;background-color:white;">
      <view style="width: 100%;margin: auto;display: flex">
        <u-image
            width="100"
            height="100"
            src="https://img01.yzcdn.cn/vant/cat.jpeg"
        />
        <view style="width: 80%;height: 100rpx">
          <view style="padding-left: 50rpx;height: 50%">
            <text style="font-size: 36rpx;font-weight: 600">{{ good.shopName }}</text>
          </view>
          <view style="padding-left: 50rpx;height: 50%;padding-top: 20rpx">
            <u-rate :count="5" v-model="value"></u-rate>
          </view>
        </view>
      </view>
    </view>
    <view >
<!--      <ai-goods-action class="addLog" :options="options" :buttons="buttons" @click="handleGoodAction"-->
<!--                       @clickButton="handleButton"></ai-goods-action>-->

      <uni-goods-nav :options="options" :fill="true" :button-group="buttonGroup" @click="onClick"
                     @buttonClick="handleButton" />
    </view>


    <echone-sku
        :show="popupShow"
        :combinations="combinations"
        :specifications="specifications"
        @close="handleClose"
        @confirm="handleConfirm"
    ></echone-sku>
  </view>

</template>

<script>
import {BASE_IMG_URL} from "../../../api/service";
import {mainService} from "../../../api/buyer/main";
import {attachmentService} from "../../../api/buyer/public/attachmentService";
import {EvaluationService} from "../../../api/buyer/public/evaluate";
import UniEvaluate from "../../../components/xiujun-evaluate/uni-evaluate";
import {NetWork} from "../../../api/buyer/common";
import {ShoppingCartService} from "../../../api/buyer/ShoppingCart/index";
export default {
  name: "goodDetailed",
  components: {UniEvaluate},
  onLoad(option) {
    const s = decodeURIComponent(option.good);
    let good = JSON.parse(s)
    console.log(good)
    this.good = good;
    this.findSpecificationsByCommodityId(good.eid)
    this.loadImg(good.eid,'Commodity')
    this.loadEvaluateImage()
  },

  data() {

    return {
      evaluateCount:0,
      value: 3,
      good: {},
      imgList: [],
      currentImg: 0, //默认展示
      update: true,
      specifications: [
        {
          name: '发证机关',
          id: '123',
          list: ['成都市锦江区', '成都市青羊区'],
        },
      ],
      combinations: [
        {
          id: '1',
          value: '成都市锦江区,2020年',
          image:
              'https://miniprogram-img01.caishuib.com/wx15168444f005a4ab/material/image/202005135/3a014c2f42c1c46b.PNG',
          price: 80.0,
          stock: 1000,
        },
      ],
      options: [
        {
          text: "客服",
          icon: 'chat',
          dot: true,
        },
        {
          text: "收藏",
          icon: 'heart',
          dot: true,
        },
        {
          text: "购物车",
          icon: 'cart',
        }
      ],
      buttonGroup: [{
        text: '加入购物车',
        backgroundColor: 'linear-gradient(90deg, #FFCD1E, #FF8A18)',
        color: '#fff'
      },
        {
          text: '立即购买',
          backgroundColor: 'linear-gradient(90deg, #FE6035, #EF1224)',
          color: '#fff'
        }
      ],
      popupShow: false,
      evaluate:[{
        imgs:[],
      }],

    }

  },
  methods: {
    loadImg(id,name){
      attachmentService.findFile(id,name).then((res)=>{
        let attachments = res.data;
        if(attachments.length){
          attachments.forEach((attachment)=>{
            this.imgList.push(BASE_IMG_URL+attachment.attachmentAddr)
          })
        }
      })
    },
    loadEvaluateImage(id,name) {
      if (id && name) {
      attachmentService.findFile(id, name).then((res) => {
        let attachments = res.data;
        let imgs = [];
        if (attachments.length) {
          attachments.forEach((attachment) => {
            imgs.push(BASE_IMG_URL + attachment.attachmentAddr)
          })
        }
        this.evaluate[0].imgs = imgs
        this.refresh()
        // console.log("evaluate",this.evaluate)
      })
    }
    },
    loadSpecificationImage(id,name){
      attachmentService.findFile(id,name).then((res)=>{
        let attachments = res.data;
        let imgs=[];
        if(attachments.length){
          attachments.forEach((attachment)=>{
            imgs.push(BASE_IMG_URL+attachment.attachmentAddr)
          })
        }
        this.evaluate[0].imgs=imgs
        this.refresh()
        console.log("evaluate",this.evaluate)
      })
    },
    findSpecificationsByCommodityId(commodityId) {
      const self = this
      mainService.findSpecificationsByCommodityId(commodityId).then((res) => {
        let spec = res.data
        let specRes = [];
        spec.forEach(item => {
          let specification = {};
          specification.name = item.description
          specification.id = item.eid;
          specification.list = [];
          item.children.forEach(subItem => {
            specification.list.push(subItem.description)
          })
          specRes.push(specification)
        })
        self.specifications = specRes;
      })
      mainService.findSpecificationStockByCommodityId(commodityId).then((res) => {
        self.good.specificationStock = res.data;
        if (res.data != undefined && res.data != null) {
          let comRes = [];
          res.data.forEach(item => {
            self.good.maxPrice = Math.max(self.good.maxPrice == undefined ? 0 : self.good.maxPrice, item.price);
            self.good.minPrice = Math.min(self.good.minPrice == undefined ? 99999999 : self.good.minPrice, item.price);
            let com = {};
            com.id = item.eid;
            com.value = item.specification;

            attachmentService.findFile(com.id,'specificationStock').then((res)=>{
              let attachments = res.data;
              if(attachments.length > 0){
                com.image=BASE_IMG_URL+attachments[0].attachmentAddr
              }else{
                com.image = "https://miniprogram-img01.caishuib.com/wx15168444f005a4ab/material/image/202005135/3a014c2f42c1c46b.PNG"
              }
            });



            com.price = item.price;
            com.stock = item.stock;
            comRes.push(com);
          })
          self.combinations = comRes;
          self.refresh()
        }
      })
      //查询评论
      let queryParams={
        currentPage:1,
        pageSize:1,
        filters:{
          commodityId:commodityId
        },
        orderBys:[
          {
            property:'createDatetime',
            order:"DESC"
          }
        ]
      }
      EvaluationService.findEvaluations(queryParams).then((res)=>{
        console.log(res.data.datas)
        if(res.data.datas.length!=0) {
          this.evaluate = res.data.datas
          this.evaluateCount = res.data.totalCount
          this.loadEvaluateImage(this.evaluate[0].eid, "evaluation")
        }else {
          this.evaluate =[];
        }
      }).catch((err)=>{
        console.log("findEvaluations",err)
      });
    },

    refresh() {
      this.update = false;
      this.update = true;
    },
    onChange(item, index) {
      console.log(item)
      console.log(index)
    },
    handleClose(item) {
      this.popupShow = false
      console.log(item)
      this.good.specification = item.value
      this.good.count = item.count
      this.good.price = item.price
    },
    handleConfirm(item) {
      console.log(item)
      this.good.specification = item.value
      this.good.count = item.count
      this.good.price = item.price
      this.buy()

    },
    openSelect() {
      console.log("open")
      this.popupShow = true
    },
    onClick(e) {
      uni.showToast({
        title: `点击${e.content.text}`,
        icon: 'none'
      })
    },
    handleButton(item) {
      // console.log(item)
      if(item.index==1){
        console.log(this.good)
        this.buy()
        return;
      }
      if(item.index==0){
        console.log("加入购物车")
        this.addShopCart();
      }
    },
    buy(){
      if(!this.good.specification&&!this.good.count&&!this.good.price){
        uni.showToast({
          title:"请选择规格"
        })
        return;
      }
      let info={
        description:this.good.description,
        eid:this.good.eid,
        specification:this.good.specification,
        count:this.good.count,
        price:this.good.price,
        url:this.imgList[0],
        shopId:this.good.shopId,
      }
      NetWork.checkIsLogin();
      console.log("info",info)
      uni.navigateTo({
        url: '/pages/buyer/main/OrderFrom?info=' + encodeURIComponent(JSON.stringify(info)),
        // url: '/pages/staff/application/production/taskList/task-detail'
      })
    },
    moreEvaluate(){
      uni.navigateTo({
        url: '/pages/buyer/public/evaluate/index?commodityId='+encodeURIComponent(JSON.stringify(this.good.eid))
            // encodeURIComponent(JSON.stringify(info)),
        // url: '/pages/staff/application/production/taskList/task-detail'
      })

    },
    addShopCart() {
      if(!this.good.specification&&!this.good.count&&!this.good.price){
        uni.showToast({
          title:"请选择规格"
        })
        return;
      }
      let info={
        commodityId:this.good.eid,
        specification:this.good.specification,
        count:this.good.count,
        shopId:this.good.shopId,
      }
      NetWork.checkIsLogin();
      ShoppingCartService.addShoppingCart(info).then((res)=>{
        uni.showToast({
          title:"加入购物车成功",
          duration:2000,
          icon:'success'
        })
      }).catch((err)=>{
        uni.showToast({
          title:"加入购物车失败",
          duration:2000,
          icon:'error'
        })
      })
    }
  }
}
</script>

<style scoped>
.position-sticky {
  position: -webkit-sticky !important;
  position: sticky !important;
}

.fixed-bottom {
  position: fixed;
  right: 0;
  bottom: calc(var(--window-bottom) + 3px);
  left: 0;
  z-index: 1030;
  margin-bottom: 6;
}

.addLog {
  position: fixed;
  bottom: calc(var(--window-bottom));
  z-index: 1030;
}
</style>